import {
  Button,
  Drawer,
  Form,
  FormInstance,
  Input,
  message,
  Modal,
  Slider,
  Space,
} from "antd";
import Dialog from "../Dialog";
import { FC, RefObject, useEffect, useRef, useState } from "react";
import Upload from "../upload";
import {
  clone,
  findIndex,
  forEach,
  get,
  has,
  isArray,
  map,
  pick,
  set,
} from "lodash";
import { BusinessItemInfo, BusinessItemListInfo } from "../../types/business";
import ElementSelectorCtrl from "./ElementSelectorCtrl";
import ImageListUpload from "./ImageListUpload";
import KeyWordCtrl from "./KeyWrodCtrl";
import { characterDialog } from "./people";
import { pictureDialog } from "./picture";
import { iconDialog } from "./icon";
import request from "../../utils/request";

const CreateAndModify: FC<{
  flag: number;
  data?: BusinessItemInfo;
  onFinish?: () => void;
}> = ({ onFinish, data, flag }) => {
  const isModify = !!data;
  const [open, setOpen] = useState(false);
  const formRef = useRef<FormInstance>();

  useEffect(() => {
    if (!flag) return;
    setOpen(true);
  }, [flag]);

  const onChange: (
    dialog: (item: any) => Promise<any>,
    fileName: string
  ) => (v?: any) => void = (dialog, fileName) => {
    return async (item, idx) => {
      const data = await dialog(item);
      const isModify = !!item;
      if (!formRef.current) return;
      const list = formRef.current.getFieldValue(fileName) || [];
      if (!isModify) {
        list.push(data);
      } else {
        list[idx] = data;
      }
      formRef.current.setFieldValue(fileName, [...list]);
    };
  };

  const onDelete = (field: string) => {
    return (item: BusinessItemListInfo, idx: number) => {
      if (!formRef.current) return;
      const list = formRef.current.getFieldValue(field) || [];
      list.splice(idx, 1);
      formRef.current.setFieldValue(field, clone(list));
    };
  };

  const onSubmit = async () => {
    if (!formRef.current) return;
    const formatData = formRef.current?.getFieldsValue();
    Object.values(formatData).forEach((group) => {
      forEach(group, (item) => {
        if (has(item, "media_info")) {
          set(
            item,
            "media_list",
            map(item.media_info, (v) => v.id || v.media_info_id)
          );
          delete item.media_info;
        }
      });
    });
    await request("pattern/info/v2", {
      method: "POST",
      data: {
        pattern_name: '',
        element_list: [],
        face_list: [],
        image_list: [],
        key_word_list: [],
        logo_list: [],
        ...data,
        ...formatData,
      },
    });
    message.success(isModify ? "更新成功" : "新建成功");
    setOpen(false);
    onFinish?.();
  };

  return (
    <Modal
      width={1000}
      open={open}
      title={isModify ? "业务模型编辑" : "业务模型创建"}
      destroyOnClose
      onCancel={() => setOpen(false)}
      onOk={onSubmit}
    >
      <Form initialValues={data} ref={formRef}>
        <Form.Item label="模型名称" name="pattern_name">
          <Input placeholder="请输入模型名称" />
        </Form.Item>
        <Form.Item label="元素选择" name="element_list">
          <ElementSelectorCtrl />
        </Form.Item>
        <Form.Item label="人物创建" name="face_list">
          <ImageListUpload
            addLabel="新增人物"
            onClick={onChange(characterDialog, "face_list")}
            onDelete={onDelete("face_list")}
            sourceAtr="media_info[0].media_url"
          />
        </Form.Item>
        <Form.Item label="图标创建" name="logo_list">
          <ImageListUpload
            addLabel="新建图标"
            onClick={onChange(iconDialog, "logo_list")}
            onDelete={onDelete("logo_list")}
            sourceAtr="media_info[0].media_url"
          />
        </Form.Item>
        <Form.Item label="图像创建" name="image_list">
          <ImageListUpload
            addLabel="新增图像"
            onClick={onChange(pictureDialog, "image_list")}
            sourceAtr="media_info[0].media_url"
            onDelete={onDelete("image_list")}
          />
        </Form.Item>
        <Form.Item label="关键词配置" name="key_word_list">
          <KeyWordCtrl />
        </Form.Item>
      </Form>
    </Modal>
  );
};

export default CreateAndModify;
